<template>
  <div>
    <el-dialog
      class="allocationRoleDialog"
      title="分配角色"
      :before-open="getRolesData"
      :visible.sync="allocationRoleDialog"
      width="31%"
    >
      <!-- 对话框主体区域 -->
      <el-radio
        v-for="(item, index) in radioRoles"
        :key="index"
        v-model="radioRolesChecked"
        :label="item.Rname"
        >{{ item.Rname }}</el-radio
      >
      <!-- 对话框底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="allocationRoleDialog = false">取 消</el-button>
        <el-button type="primary" @click="allocationRole()">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="添加用户" :visible.sync="dialogFormVisible" width="40%">
      <!-- 对话框主体区域 -->
      <el-form
        :model="addUser"
        :rules="addUserRules"
        ref="addUserFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名:" prop="Uname">
          <el-input v-model="addUser.Uname"></el-input>
        </el-form-item>
        <el-form-item label="密码:" prop="Upwd">
          <el-input type="password" v-model="addUser.Upwd"></el-input>
        </el-form-item>
        <el-form-item disabled="true" label="邮箱:" prop="Email">
          <el-input v-model="addUser.Email"></el-input>
        </el-form-item>
        <el-form-item label="电话:" prop="Uphone">
          <el-input v-model="addUser.Uphone"></el-input>
        </el-form-item>
      </el-form>
      <!-- 对话框底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="ai_dialog_close()">取 消</el-button>
        <el-button type="primary" @click="addUserInfo()">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="修改用户"
      :visible.sync="dialogFormUpdate"
      :before-close="update_dialog_close"
      width="40%"
    >
      <!-- 对话框主体区域 -->
      <el-form
        :model="updateUser"
        :rules="updateUserRules"
        ref="updateUserRules"
        label-width="70px"
      >
        <el-form-item label="用户名:" prop="Uname">
          <el-input v-model="updateUser.Uname" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="邮箱:" prop="Email">
          <el-input v-model="updateUser.Email"></el-input>
        </el-form-item>
        <el-form-item label="电话:" prop="Uphone">
          <el-input v-model="updateUser.Uphone"></el-input>
        </el-form-item>
      </el-form>
      <!-- 对话框底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="update_dialog_close()">取 消</el-button>
        <el-button type="primary" @click="updateUserInfo()">确 定</el-button>
      </span>
    </el-dialog>
    <div class="tab">
      <!-- 卡片视图区域 -->
      <el-card>
        <!-- 搜索与添加区域 -->
        <el-row>
          <el-col :span="6">
            <el-input
              size="small"
              v-model="searchName"
              placeholder="请输入查找的用户名"
            >
              <el-button
                slot="append"
                @click="searchByName"
                icon="el-icon-search"
              ></el-button>
            </el-input>
          </el-col>
          <el-col :span="2">
            <el-button
              size="small"
              icon="el-icon-delete"
              type="primary"
              @click="dialogFormVisible = true"
              >添加用户</el-button
            >
          </el-col>
          <el-col :span="2">
            <el-button
              type="danger"
              @click="batchDel()"
              icon="el-icon-delete"
              size="small"
              >批量删除</el-button
            >
          </el-col>
        </el-row>
      </el-card>
      <el-table
        @selection-change="selectionChange"
        :data="paginationList"
        border
      >
        <el-table-column
          type="selection"
          align="center"
          prop="checked"
          width="65"
        ></el-table-column>
        <el-table-column
          type="index"
          align="center"
          prop="id"
          width="65"
        ></el-table-column>

        <el-table-column
          prop="Uname"
          align="center"
          label="用户名"
          width="88"
        ></el-table-column>
        <el-table-column
          prop="Email"
          align="center"
          label="邮箱"
        ></el-table-column>
        <el-table-column
          prop="Uphone"
          align="center"
          label="电话"
        ></el-table-column>
        <el-table-column
          prop="Rname"
          align="center"
          label="角色"
        ></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.Ustate"
              @change="changeState(scope.row)"
            ></el-switch> </template
        ></el-table-column>
        <el-table-column prop="operate" align="center" width="200" label="操作">
          <template slot-scope="scope">
            <!-- 修改 -->
            <el-button
              type="text"
              @click="openDialogFormUpdate(scope.row)"
              icon="el-icon-edit"
              size="mini"
              >编辑</el-button
            >
            <!-- 删除 -->
            <el-button
              class="danger"
              type="text"
              @click="openDel(scope.row.Uid)"
              icon="el-icon-delete"
              size="mini"
              >删除</el-button
            >
            <!-- 分配角色 -->
            <el-button
              @click="openAllocationRoleDialog(scope.row)"
              type="text"
              class="warning"
              icon="el-icon-setting"
              size="mini"
              >分配角色</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="paginationBlock" style="margin-top: 15px">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[7, 15, 20, 25]"
          :page-size="pageSize"
          layout="total,sizes, prev, pager, next,jumper"
          :total="userList.length"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      allocationRoleDialog: false, //分配角色的模态框
      paginationList: [], // 此数组会由getlivestockInfo()函数调用由userList[]数组提取的部分数据存入来控制页面显示数据条数
      userList: [], // 此数组为table表格的完整数据源
      currentPage: 1, //当前页码
      pageSize: 7, //每页的数据条数
      dialogFormVisible: false,
      dialogFormUpdate: false,
      addUser: {
        Uname: "",
        Email: "",
        Uphone: "",
        Upwd: "",
      },
      updateUser: {
        Uid: "",
        Uname: "",
        Email: "",
        Uphone: "",
        Email: "",
        Upwd: "",
      },
      searchName: "",
      updateUserRules: {
        Email: [
          { required: true, message: "请输入您的电子邮箱", trigger: "blur" },
          {
            validator: function (rule, value, callback) {
              if (
                /^\w{1,64}@[a-z0-9\-]{1,256}(\.[a-z]{2,6}){1,2}$/i.test(
                  value
                ) == false
              ) {
                callback(new Error("邮箱格式错误"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        Uphone: [
          { required: true, message: "请输入您的电话号码", trigger: "blur" },
          {
            validator: function (rule, value, callback) {
              if (/^1[34578]\d{9}$/.test(value) == false) {
                callback(new Error("手机号格式错误"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
      },
      addUserRules: {
        Uname: [
          { required: true, message: "请输入您的用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在3到10个字符之间",
            trigger: "blur",
          },
        ],
        Upwd: [
          { required: true, message: "请输入您的密码", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在3到10个字符之间",
            trigger: "blur",
          },
        ],
        Email: [
          { required: true, message: "请输入您的电子邮箱", trigger: "blur" },
          {
            validator: function (rule, value, callback) {
              if (
                /^\w{1,64}@[a-z0-9\-]{1,256}(\.[a-z]{2,6}){1,2}$/i.test(
                  value
                ) == false
              ) {
                callback(new Error("邮箱格式错误"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        Uphone: [
          { required: true, message: "请输入您的电话号码", trigger: "blur" },
          {
            validator: function (rule, value, callback) {
              if (/^1[345789]\d{9}$/.test(value) == false) {
                callback(new Error("手机号格式错误"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
      },
      selectionList: [],
      radioRoles: [], //单选框中角色数据
      radioRolesChecked: "单选框选择的角色",
      updateRoleUserId: "", //修改角色的用户id
    };
  },
  methods: {
    // 获取用户数据
    getlivestockInfo() {
      let that = this;
      that.$axios
        .post("http://localhost:8080/UserServiceAll", {
          headers: { "Content-Type": "application/x-www-form-urlencoded" },
        }) //补上后台接口即可
        .then((res) => {
          // 请求成功
          that.userList = res.data;
          // 获取页面数据后立马调用下面函数
          that.getPageData();
          return;
        })
        .catch((error) => {
          // 请求失败
          console.log("请求失败");
          console.log(error);
        });
    },
    // 获取分页之后的数据
    getPageData() {
      let start = (this.currentPage - 1) * this.pageSize;
      let end = start + this.pageSize;
      this.paginationList = this.userList.slice(start, end);
    },
    // 每页条数改变时触发 选择一页显示多少行
    handleSizeChange(val) {
      this.pageSize = val;
      this.getPageData();
    },
    // 当前页改变时触发 跳转其他页
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getPageData();
    },
    changeState(row) {
      let that = this;
      var params = new URLSearchParams();
      params.append("changeUid", row.Uid);
      params.append("uState", row.Ustate);
      that.$axios
        .post(`http://localhost:8080/ChangeUserState`, params)
        .then(() => {
          // 请求成功
          this.getlivestockInfo();
        })
        .catch((error) => {
          // 请求失败
          console.log("请求失败");
          console.log(error);
        });
    },
    // 打开删除弹出框
    openDel(targetId) {
      let that = this;
      this.$confirm("此操作将永久删除该条信息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          var params = new URLSearchParams();
          params.append("delUid", targetId);
          that.$axios
            .post("http://localhost:8080/DelUserInfo", params)
            .then((res) => {
              // 请求成功
              this.getlivestockInfo();
              this.$message({
                type: "success",
                message: "删除成功!",
              });
            })
            .catch((error) => {
              // 请求失败
              console.log("请求失败");
              console.log(error);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 关闭修改添加模态窗
    ai_dialog_close() {
      this.clearAddDilog();
      this.dialogFormVisible = false;
      this.$refs["addUserFormRef"].clearValidate();
    },
    update_dialog_close() {
      this.clearUpdateDilog();
      this.dialogFormUpdate = false;
      // this.$refs.updateUserRules.clearValidate();
      this.$refs.updateUserRules.resetFields();
    },
    // 添加用户信息
    addUserInfo() {
      this.$refs.addUserFormRef.validate(async (valid) => {
        var params = new URLSearchParams();
        params.append("Uname", this.addUser.Uname);
        params.append("Upassword", this.addUser.Upwd);
        params.append("Email", this.addUser.Email);
        params.append("Uphone", this.addUser.Uphone);
        if (!valid) return this.$message.error("请正确填写用户信息");
        await this.$axios
          .post("http://localhost:8080/AddUserInfo", params, {
            headers: {
              "Content-Type": "application/x-www-form-urlencoded",
              "Access-Control-Allow-Origin": "*",
            },
          })
          .then((sfw) => {
            this.$message.success({
              type: "success",
              message: sfw.data,
            });
            this.getlivestockInfo();
            this.ai_dialog_close();
          })
          .catch((error) => {
            console.log(error);
          });
      });
    },
    // 清空修改添加模态框
    clearAddDilog() {
      this.addUser.Uname = "";
      this.addUser.Email = "";
      this.addUser.Uphone = "";
      this.addUser.Upwd = "";
    },
    // 清空修改模态框
    clearUpdateDilog() {
      this.updateUser.Uname = "";
      this.updateUser.Email = "";
      this.updateUser.Uphone = "";
    },
    // 打开修改模态框
    openDialogFormUpdate(row) {
      this.dialogFormUpdate = true;
      this.updateUser.Uid = row.Uid;
      this.updateUser.Uname = row.Uname;
      this.updateUser.Email = row.Email;
      this.updateUser.Uphone = row.Uphone;
    },
    // 修改用户信息
    updateUserInfo() {
      this.$refs.updateUserRules.validate(async (valid) => {
        if (!valid) return this.$message.error("请正确填写修改用户信息");
        await this.$axios
          .post("/UpdateUserInfoById", this.updateUser)
          .then((res) => {
            if (res.data > 0) {
              this.$message.success({
                type: "success",
                message: "修改成功",
              });
            } else {
              this.$message.error("修改失败");
            }
            this.getlivestockInfo();
            this.update_dialog_close();
          })
          .catch((error) => {
            console.log(error);
          });
      });
    },
    // 批量删除
    batchDel() {
      let that = this;
      if (that.selectionList.length > 0) {
        that
          .$confirm("此操作将永久删除该条信息, 是否继续?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
          .then(() => {
            var params = new URLSearchParams();
            params.append("selectionListId", that.selectionList);
            that.$axios
              .post("http://localhost:8080/BatchDel", params)
              .then(() => {
                that.getlivestockInfo();
                that.$message({
                  type: "success",
                  message: "删除成功!",
                  duration: 2000, // 设置显示时间为2秒
                });
              })
              .catch((error) => {
                // 请求失败
                console.log("请求失败");
                console.log(error);
              });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
              duration: 2000, // 设置显示时间为2秒
            });
          });
      } else {
        this.$message({
          type: "warning",
          message: "至少要选择一项",
          duration: 1000, // 设置显示时间为1秒
        });
      }
    },
    // 选择改变
    selectionChange(selection) {
      this.selectionList = [];
      // 表格选项发生变化
      selection.forEach((element) => {
        this.selectionList.push(element.Uid);
      });
    },
    // 通过用户名查询
    searchByName() {
      if (this.searchName === "") {
        this.getlivestockInfo();
      } else {
        let params = new URLSearchParams();
        params.append("searchName", this.searchName);
        this.$axios
          .post("http://localhost:8080/UserSearchByname", params)
          .then((res) => {
            this.userList = res.data;
            this.getPageData();
          })
          .catch((err) => {
            console.log(err);
          });
      }
    },
    // 通过用户id获取角色数据
    getRoleDataByUserId() {
      let that = this;
      that.$axios
        .get(
          `http://localhost:8080/getRoleDataByUserId?Uid=${this.updateRoleUserId}`
        ) //补上后台接口即可
        .then((res) => {
          // 请求成功
          that.radioRolesChecked = res.data.Rname;
        })
        .catch((error) => {
          // 请求失败
          console.log("请求失败");
          console.log(error);
        });
    },
    // 获取角色数据
    getRolesData() {
      let that = this;
      that.$axios
        .post("http://localhost:8080/RolesServiceAll") //补上后台接口即可
        .then((res) => {
          // 请求成功
          that.radioRoles = res.data;
        })
        .catch((error) => {
          // 请求失败
          console.log("请求失败");
          console.log(error);
        });
    },
    // 分配角色确定按钮
    allocationRole() {
      //调用修改用户角色接口
      let params = new URLSearchParams();
      params.append("Uid", this.updateRoleUserId);
      params.append("radioRolesChecked", this.radioRolesChecked);
      this.$axios
        .post("http://localhost:8080/updateUsersRoleId", params)
        .then((res) => {
          this.getlivestockInfo();
          this.allocationRoleDialog = false;
          if (res.data > 0) {
            this.$message.success({
              type: "success",
              message: "修改成功",
            });
          } else {
            this.$message.error("修改失败");
          }
        })
        .catch((err) => {
          console.log(err);
          console.log("请求出错了");
        });
    },
    //打开分配角色模态框
    openAllocationRoleDialog(row) {
      this.updateRoleUserId = row.Uid;
      this.allocationRoleDialog = true;
      this.getRoleDataByUserId();
    },
  },
  mounted() {
    this.getlivestockInfo();
    this.getRolesData();
  },
};
</script>

<style>
@import "../../../assets/css/PublicStyle.css";
.paginationBlock {
  margin-left: 90px;
}
.el-card .el-col {
  margin-right: 8px;
}
.allocationRoleDialog .el-dialog__body {
  padding: 15px 35px;
}
</style>
